//
//  PrescriptionOrderViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/2.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import Foundation
import HandyJSON

class PrescriptionOrderViewModel: NSObject {
    
    var updateClosure: ((HttpCode) -> ())?
    var changeClosure: (() -> ())?
    
    private(set) var items: [PrescriptionOrderCellViewModel] = []
    
    var showEmptyView: Bool { return items.count <= 0 }
    
    var numberOfRows: Int { items.count }
    
    func viewModel(for indexPath: IndexPath) -> PrescriptionOrderCellViewModel {
        return items[indexPath.row]
    }
    
    var hasMore: Bool = true
    
    func cellHeight(at indexPath: IndexPath) -> CGFloat {
        let viewModel = viewModel(for: indexPath)
        return viewModel.cellHeight
    }
    
    var headerHeight: CGFloat { 8 }
    
    private var current: Int = 1
    
    func loadData(_ more: Bool = false) {
        current = more ? current + 1 : 1
        
        getPrescriptionOrderList(more)
    }
    
    /// 获取处方订单列表
    private func getPrescriptionOrderList(_ more: Bool) {
        let target = ApiManager.prescriptionOrderList(current: current)
        HttpTool.shared.request(target: target, success: { (json, code) in
            YSGLog("处方药品订单: \(json)")
            switch code {
            case .failure:
                HUDTool.showError(message: json["message"].description)
            case .success:
                if let model = PrescriptionOrderList.deserialize(from: json["data"].description) {
                    let items = (model.records ?? []).map { PrescriptionOrderCellViewModel(model: $0) }
                    
                    more ? (self.items += items) : (self.items = items)
                    
                    self.hasMore = model.pages > model.current
                }
            }
            self.updateClosure?(code)
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
            self.updateClosure?(.failure)
        }
    }
    
    func changePrescriptionOrderStatus(_ status: PrescriptionOrderStatus, at indexPath: IndexPath) {
        HUDTool.showActivity()
        let viewModel = viewModel(for: indexPath)
        let target = ApiManager.updatePrescriptionOrderStatus(id: viewModel.prescriptionId, status: status.rawValue, backWaybillNo: "", backLogistics: "")
        HttpTool.shared.request(target: target) { json, code in
            YSGLog("更新处方订单状态: \(json)")
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: json["message"].description)
            case .success:
                self.changeClosure?()
            }
        } failure: { error in
            HUDTool.hideActivity()
            HUDTool.showError(message: error)
        }
    }
}
